package utils

import (
	"crypto/aes"
	"crypto/cipher"
)

//密钥
var gcm_key = []byte{
	0xe8, 0xb3, 0xb8, 0x3c, 0x2e, 0x07, 0x0d, 0x55, 0xb9, 0x98, 0x13, 0x97,
	0x9b, 0xc2, 0x9b, 0xcb, 0x1c, 0x05, 0x54, 0xc5, 0x34, 0xf8, 0xd4, 0xde,
	0x67, 0x64, 0xea, 0x85, 0x1d, 0xba, 0xa0, 0x75}

//初始向量
var Gcm_iv = []byte{
	0x44, 0xb1, 0x01, 0x07, 0xc9, 0x4f, 0xc9, 0x30, 0x8b, 0xb2, 0xf6, 0xba}

var Gcm_Arr = []gcmItem{
	{
		Aad: []byte{
			0x3a, 0x16, 0x28, 0x3d, 0x30, 0x08, 0x10, 0x98, 0xcb, 0x87, 0x6d, 0xd9,
			0xf0, 0x62, 0x8c, 0x3f},
		Iv: []byte{
			0x44, 0xb1, 0x01, 0x07, 0xc9, 0x4f, 0xc9, 0x30, 0x8b, 0xb2, 0xf6, 0xba},
	},
}

type gcmItem struct {
	Aad []byte
	Iv  []byte
}

//明文
var gcm_pt = []byte{
	0xf5, 0x6e, 0x87, 0x05, 0x5b, 0xc3, 0x2d, 0x0e, 0xeb, 0x31, 0xb2, 0xea,
	0xcc, 0x2b, 0xf2, 0xa5}

//附加数据（考虑用messageId）
var Gcm_aad = []byte{
	0x3a, 0x16, 0x28, 0x3d, 0x30, 0x08, 0x10, 0x98, 0xcb, 0x87, 0x6d, 0xd9,
	0xf0, 0x62, 0x8c, 0x3f}

//密文
var Gcm_ct = []byte{
	0xf7, 0x26, 0x44, 0x13, 0xa8, 0x4c, 0x0e, 0x7c, 0xd5, 0x36, 0x86, 0x7e,
	0xb9, 0xf2, 0x17, 0x36}

//校验位（golang默认会拼接在密文后面）
var gcm_tag = []byte{
	0x67, 0xba, 0x05, 0x10, 0x26, 0x2a, 0xe4, 0x87, 0xd7, 0x37, 0xee, 0x62,
	0x98, 0xf7, 0x7e, 0x0c}

// PKCS5Padding PKCS5包装
//func PKCS5Padding(cipherText []byte, blockSize int) []byte {
//	padding := blockSize - len(cipherText)%blockSize
//	padText := bytes.Repeat([]byte{byte(padding)}, padding)
//	return append(cipherText, padText...)
//}

// PKCS5Trimming PKCS5解包装
func PKCS5Trimming(encrypt []byte) []byte {
	padding := encrypt[len(encrypt)-1]
	return encrypt[:len(encrypt)-int(padding)]
}

func AesGcmEncrypt(plaintext, aad, nonce []byte) ([]byte, error) {
	block, err := aes.NewCipher(gcm_key)
	if err != nil {
		return nil, err
	}
	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	packed := PKCS5Padding(plaintext, aes.BlockSize)
	ciphertext := aesgcm.Seal(nil, nonce, packed, aad)
	return ciphertext, nil
}

func AesGcmDecrypt(ciphertext, aad, nonce []byte) ([]byte, error) {
	block, err := aes.NewCipher(gcm_key)
	if err != nil {
		return nil, err
	}
	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	plaintext, err := aesgcm.Open(nil, nonce, ciphertext, aad)
	if err != nil {
		return nil, err
	}
	plaintext = PKCS5Trimming(plaintext)
	return plaintext, nil
}

func main() {
	ciphertext, err := AesGcmEncrypt(gcm_pt, Gcm_aad, Gcm_iv)
	if err != nil {
		panic(err)
	}
	_, err = AesGcmDecrypt(ciphertext, Gcm_aad, Gcm_iv)
	if err != nil {
		panic(err)
	}
	//_, err = aesGcmDecrypt(gcm_ct, gcm_aad, gcm_iv)
	//if err != nil {
	//	panic(err)
	//}
}
